#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<vector>
#include<string>

using namespace std;

#define Num 3

int* get;//全局指针变量

//__thread int g_val=0;
__thread int g_val;

//线程数据
struct thread_data{
    string threadname;
};

void Init(thread_data*td,int i)
{
    td->threadname="thread-"+to_string(i);
}

//转换为16进制
string tohex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer,sizeof(buffer),"0x%x",tid);

    return buffer;
}

//线程入口函数，此函数为可重入函数
void* routine(void*arg)
{
    thread_data* td=static_cast<thread_data*> (arg);//获取参数
    int i=0;
    //int test_i=0;
    //线程判断
    // if(td->threadname=="thread-2")
    // {
    //     get=&test_i;
    // }
    int g_val=pthread_self();
    int tt=g_val;
    while(i<10)
    {
        //test_i++;
        // cout<<"pid:"<<getpid()<<",name:"<<td->threadname
        // <<",tid:"<<tohex(pthread_self())<<",i:"<<i
        // <<",test_i:"<<test_i<<",&test_i:"<<tohex((pthread_t)&test_i)<<endl;//测试独立栈
        // cout<<"pid:"<<getpid()<<",name:"<<td->threadname
        // <<",tid:"<<pthread_self()<<",i:"<<i
        // <<",g_val:"<<g_val<<",&g_val:"<<&g_val<<endl;//测试独立栈
         cout<<"pid:"<<getpid()<<",name:"<<td->threadname
         <<",tid:"<<tohex(pthread_self())<<",g_val:"<<tohex(g_val)
         <<",&g_val:"<<&g_val<<",tt:"<<tohex(tt)<<endl;
        // i++,g_val++;
        sleep(1);
    }

    return nullptr;
}

int main()
{
    //保存tid方便后续线程等待
    vector<pthread_t> tids;

    //创建线程
    for(int i=1;i<=Num;i++)
    {
        pthread_t tid;
        thread_data* td=new thread_data();//错误写法thread_data td；td是当前作用域的局部变量，后续会销毁，&td时会出现错误
        Init(td,i);//初始化

        pthread_create(&tid,nullptr,routine,td);

        tids.push_back(tid);
    }

    //sleep(1);//确保线程创建完毕
    //cout<<"main pthread;test_i:"<<*get<<",&test_i:"<<tohex((pthread_t)get)<<endl;

    //线程等待
    for(int i=0;i<tids.size();i++)
    {
        pthread_join(tids[i],nullptr);
    }

    return 0;
}